package admin

import (
	"Web-Shop/controllers/base"
	"path"
	"strconv"
	"time"

	"github.com/astaxie/beego"
	"github.com/weilaihui/fdfs_client"
)

type AdminController struct {
	base.BaseController
}

func init() {
	beego.AddFuncMap("prepage", ShowPrePage)
	beego.AddFuncMap("nextpage", ShowNextPage)
}

func (c *AdminController) UploadFile(uploadname string, uploadToFastDFS ...bool) string {
	file, head, err := c.GetFile(uploadname)
	if err != nil {
		beego.Info("文件上传发生错误")
		return "no_img"
	}
	defer file.Close()

	if head.Size > 50000000 {
		c.Data["errmsg"] = "文件过大，上传失败"
		return "no_img"
	}

	c.Data["test"] = "这是一个测试"

	ext := path.Ext(head.Filename)
	if ext != ".jpg" && ext != ".png" && ext != ".jpeg" {
		c.Data["errmsg"] = "文件格式错误。请重新上传"
		return "no_img"
	}

	if len(uploadToFastDFS) > 0 && uploadToFastDFS[0] {
		client,err:=fdfs_client.NewFdfsClient("conf/fdfs.client.conf")
		if err!=nil{
			beego.Info("fdfs连接失败",err)
			return "no_img"
		}
		fileBuffer:=make([]byte,head.Size)
		file.Read(fileBuffer)
		res,err:=client.UploadByBuffer(fileBuffer,ext[1:])
		if err!=nil{
			beego.Info("上传失败",err)
			return "no_img"
		}
		return "http://www.rechengparty.com:8888/"+res.RemoteFileId
	} else {
		fileName := path.Join("static/upload/" + head.Filename + strconv.Itoa(int(time.Now().Unix())) + ext)
		if err := c.SaveToFile(uploadname, fileName); err != nil {
			beego.Info("文件上传失败啦", err)
		}
		return "/" + fileName
	}
}

func ShowPrePage(page int) int {
	if page == 1 {
		return page
	}
	return page - 1
}

func ShowNextPage(page int, pageCount int) int {
	if page == pageCount {
		return page
	}
	return page + 1
}
